import axios from 'axios'
import useCommonStore from '../stores/common.js'
import router from '../router/index.js'
import { storeToRefs } from 'pinia'
import { createUuid, decrypt, encrypt, getEncrypt } from '@/utils/encryp'
import { appId } from '@/config'
import useUserStore from '@/stores/user'
import { message } from 'ant-design-vue'
import { addPendingRequest, removePendingRequest } from '@/utils/requestMap'

const notTokenUrls = ['/shell/GetCheckCodeImage', '/shell/SysLogin'] // 验证码接口不要传token防止存的token过期导致接口调用鉴权失败
const service = axios.create({
  // baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 300000
})

// 不要加密的白名单
const noEncryptWhite = []
// 可以重复发起请求的url白名单
const canRepeatUrl = []

service.interceptors.request.use(
  async (config) => {
    config.url = window.baseUrl + config.url
    const commonStore = useCommonStore()
    if (!canRepeatUrl.includes(config.url)) {
      addPendingRequest(config)
    }
    // commonStore.addUrl(config.url);
    if (noEncryptWhite.some((it) => config.url.indexOf(it) !== -1)) {
      return config
    }
    const key = createUuid()
    const iv = createUuid(16)
    if (import.meta.env.MODE === 'development') {
      console.log(`%c请求参数(${config.url}):`, 'color:orange', config.data)
    }

    if (
      config.url.indexOf('UploadSheetModel') === -1 &&
      config.url.indexOf('execution/workOrder/uploadFile') === -1
    ) {
      config.data = encrypt(JSON.stringify(config.data || {}), key, iv)
    }
    const oid = createUuid(16)

    const otp = await getEncrypt(key, iv, !notTokenUrls.includes(config.url))
    commonStore.addRequestKes(oid, { key, iv })
    config.headers['sqyd-req-otp'] = otp
    config.headers['sqyd-req-oid'] = oid
    config.headers['sqyd-req-appid'] = appId
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    if (!canRepeatUrl.includes(response.config.url)) {
      removePendingRequest(response.config)
    }
    if (noEncryptWhite.some((it) => response.config.url.indexOf(it) !== -1)) {
      return response.data
    }
    const oid = response.headers['sqyd-resp-oid']
    const commonStore = useCommonStore()
    const { token, userInfo } = storeToRefs(useUserStore())
    let requestKeys = commonStore.requestKeys
    if (oid && requestKeys[oid]) {
      const status = response.headers['sqyd-resp-status']
      if (status === 'OK') {
        const { key, iv } = requestKeys[oid]
        commonStore.removeRequestKeys(oid)
        let res = ''
        if (
          response.request.responseURL.indexOf('DownloadSheetModel') === -1 &&
          response.request.responseURL.indexOf('DownloadSheet') === -1 &&
          response.request.responseURL.indexOf('GetFile') === -1 &&
          response.request.responseURL.indexOf('SummaryProjectDataAndDownload') === -1 &&
          response.request.responseURL.indexOf('execution/workOrder/getUploadFileUrl') === -1
        ) {
          // 如果不是获取图片需要解密
          res = decrypt(response.data, key, iv)
        } else {
          // 如果是文件资源
          res = window.URL.createObjectURL(response.data)
        }
        if (
          res &&
          response.request.responseURL.indexOf('SendCheckCode') === -1 &&
          response.request.responseURL.indexOf('SendLoginCheckCode') === -1 &&
          response.request.responseURL.indexOf('DownloadSheetModel') === -1 &&
          response.request.responseURL.indexOf('DownloadSheet') === -1 &&
          response.request.responseURL.indexOf('GetFile') === -1 &&
          response.request.responseURL.indexOf('SummaryProjectDataAndDownload') === -1 &&
          response.request.responseURL.indexOf('execution/workOrder/getUploadFileUrl') === -1
        ) {
          // 如果不是图片 也不是 二维码 就需要解密
          res = JSON.parse(res)
        }

        if (import.meta.env.MODE === 'development') {
          console.log(`%c响应数据${response.request.responseURL.substring(28)}`, 'color:green', res)
        }
        return res
      } else if (status === 'E1003') {
        //
        userInfo.value = null
        token.value = ''
        message.error('登录超时')
        let url = `/login?redirect=${document.URL.substring(document.URL.indexOf('#') + 1)}`
        router.replace(url).then(() => {
          location.reload() // 这个是为了解决过期重登后线上环境vue底层报错(没找到具体原因)
        })
      } else {
        message.error(response.data)
        return Promise.reject(response)
      }
    } else {
      return Promise.reject(response)
    }
  },
  (error) => {
    console.log(error)
    if (!canRepeatUrl.includes(error.config.url)) {
      removePendingRequest(error.config || {})
    }
    if (axios.isCancel(error)) {
      // console.log("已取消的重复请求");
    } else {
      console.log(`%c响应error`, 'color:red', error)
    }
    return Promise.reject(error)
  }
)

export default service
